﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OracleClient;
using System.Globalization;
using System.Text.RegularExpressions;


public partial class bas_dept : BasePermissionPage
{
    SqlDataSource SDS_dept = new SqlDataSource();
    DataView dv = new DataView();
    protected void Page_Load(object sender, EventArgs e)
    {
        //== 1.連結資料庫的連接字串 ConnectionString  ，事先已經寫在 Web.Config檔案裡面了==
        SDS_dept.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SDS_dept.ProviderName = "Oracle.DataAccess.Client";
        SDS_dept.CancelSelectOnNullParameter = false;
        //SDS_dept.Updated += new SqlDataSourceStatusEventHandler(SDS_dept_Updated);
        //SDS_dept.Updating += new SqlDataSourceCommandEventHandler(SDS_dept_Updating);

        if (!IsPostBack)
        {
            //DBINIT();
        }
        else
        {

        }
    }
    protected void DBINIT()
    {
        try
        {
            string v_DEPT_ID, v_SQL, v_DEPT_NAME;
            DataSourceSelectArguments args = new DataSourceSelectArguments();


            v_DEPT_ID = txtDEPT_ID.Text.Trim();
            v_DEPT_NAME = txtDEPT_NAME.Text.Trim();
            //== 2.撰寫SQL指令 ==
            v_SQL = "SELECT A.DEPT_ID,A.DEPT_NAME,A.PARENT_DEPT_ID,A.E_MAIL,A.USER_ID,B.USER_NAME , A.USER_ID || '-' || B.USER_NAME as USER_ID_NAME ";
            v_SQL = v_SQL + " FROM MIS_DEPT_AP A left join MIS_USER_AP B on A.USER_ID = B.USER_ID ";
            v_SQL = v_SQL + " Where (A.DEPT_ID like :DEPT_ID) and (A.DEPT_NAME like :DEPT_NAME)  ";
            v_SQL = v_SQL + " order by A.DEPT_ID ";
            SDS_dept.SelectParameters.Clear();
            SDS_dept.SelectCommand = v_SQL;
            SDS_dept.SelectParameters.Add("DEPT_ID", TypeCode.String, v_DEPT_ID + "%");
            SDS_dept.SelectParameters.Add("DEPT_NAME", TypeCode.String, "%" + v_DEPT_NAME + "%");

            //== 3.執行SQL指令 .select() ==
            SDS_dept.DataSourceMode = SqlDataSourceMode.DataSet;

            dv = (DataView)SDS_dept.Select(args);
            //dv.AddNew();
            DV1.DataSource = dv;
            DV1.DataBind();
        }
        catch (Exception ex)
        {
            //Response.Write(e.Message);
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DBINIT", ex.Message, "", "c#", "0", ex.StackTrace);

        }
    }
    protected void DV1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {

            DV1.EditIndex = e.NewEditIndex;
            DBINIT();
        }
        catch (Exception ex)
        {
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DV1_RowEditing", ex.Message, "", "c#", "0", ex.StackTrace);
        }
    }
    protected void DV1_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        try
        {
            lbl_Message.Text = "";
            DV1.EditIndex = -1;
            DBINIT();
        }
        catch (Exception ex)
        {
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DV1_ItemCanceling", ex.Message, "", "c#", "0", ex.StackTrace);
        }
    }
    protected void DV1_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        try
        {

            DV1.EditIndex = e.NewEditIndex;
            DBINIT();
        }
        catch (Exception ex)
        {
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DV1_ItemEditing", ex.Message, "", "c#", "0", ex.StackTrace);
        }
    }
    protected void DV1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        int index;
        string v_DEPT_ID, v_DEPT_NAME, v_PARENT_DEPT_ID, v_E_MAIL, v_USER_ID, v_COLUMN = "";
        string p_return_string;
        TextBox TB = new TextBox();
        try
        {
            index = e.ItemIndex;
            v_DEPT_ID = (string)DV1.DataKeys[index].Value;
            // EmptyDataTemplate
            v_DEPT_NAME = ((TextBox)DV1.EditItem.FindControl("txtDEPT_NAME_G")).Text.Trim();
            v_PARENT_DEPT_ID = ((TextBox)DV1.EditItem.FindControl("txtPARENT_DEPT_ID")).Text.Trim();
            v_E_MAIL = ((TextBox)DV1.EditItem.FindControl("txtE_MAIL")).Text.Trim();
            v_USER_ID = ((TextBox)DV1.EditItem.FindControl("txtUSER_ID")).Text.Trim();

            lbl_Message.Text = string.Empty;
            p_return_string = check(v_PARENT_DEPT_ID, v_E_MAIL, v_USER_ID, v_DEPT_ID);
            if (p_return_string != string.Empty)
            {
                switch (p_return_string)
                {
                    case "1":
                        lbl_Message.Text = "上層部門代號必需存在於部門代號檔中!";
                        v_COLUMN = "txtPARENT_DEPT_ID";
                        break;
                    case "2":
                        lbl_Message.Text = "上層部門代號必需存在於部門代號檔中!";
                        v_COLUMN = "txtPARENT_DEPT_ID";
                        break;
                    case "3":
                        lbl_Message.Text = "使用者代號必需存在於使用者檔中!";
                        v_COLUMN = "txtUSER_ID";
                        break;
                    case "4":
                        lbl_Message.Text = v_PARENT_DEPT_ID + "-與部門代號(" + v_DEPT_ID + ")產生循環參考！";
                        v_COLUMN = "txtPARENT_DEPT_ID";
                        break;
                    default:
                        break;
                }


                TB = ((TextBox)DV1.EditItem.FindControl(v_COLUMN));
                TB.Focus();
                e.Cancel = true;
            }
            else
            {

                //'==下面的程式，只是作SQL指令的更新動作而已
                //'== 設定SQL指令將會用到的參數 ==
                SDS_dept.UpdateParameters.Clear();
                SDS_dept.UpdateParameters.Add("DEPT_NAME", v_DEPT_NAME);
                SDS_dept.UpdateParameters.Add("PARENT_DEPT_ID", v_PARENT_DEPT_ID);
                SDS_dept.UpdateParameters.Add("E_MAIL", v_E_MAIL);
                SDS_dept.UpdateParameters.Add("USER_ID", v_USER_ID);
                SDS_dept.UpdateParameters.Add("UPD_ID", User.Identity.Name);
                SDS_dept.UpdateParameters.Add("UPD_DATE", System.DateTime.Now.ToString("yyyyMMdd"));
                SDS_dept.UpdateParameters.Add("UPD_TIME", System.DateTime.Now.ToString("HHmmss"));
                SDS_dept.UpdateParameters.Add("DEPT_ID", v_DEPT_ID);

                SDS_dept.UpdateCommand = "UPDATE MIS_DEPT_AP SET DEPT_NAME = :DEPT_NAME, PARENT_DEPT_ID = :PARENT_DEPT_ID, E_MAIL = :E_MAIL, USER_ID = :UESR_ID, UPD_ID = :UPD_ID, UPD_DATE = :UPD_DATE, UPD_TIME = :UPD_TIME WHERE DEPT_ID = :DEPT_ID";
                SDS_dept.Update();
                //'==========================================
                //'==== 離開編輯模式 ====
                DV1.EditIndex = -1;
                DBINIT();
            }

        }
        catch (Exception ex)
        {
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DV1_ItemUpdating", ex.Message, "", "c#", "0", ex.StackTrace);
        }
    }
    protected void DV1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        int index;
        string v_DEPT_ID;
        try
        {
            index = e.ItemIndex;
            v_DEPT_ID = (string)DV1.DataKeys[index].Value;

            //'==下面的程式，只是作SQL指令的更新動作而已
            //'== 設定SQL指令將會用到的參數 ==
            SDS_dept.DeleteParameters.Add("DEPT_ID", v_DEPT_ID);
            SDS_dept.DeleteCommand = "Delete MIS_DEPT_AP Where DEPT_ID = :DEPT_ID";
            SDS_dept.Delete();
            DBINIT();

        }
        catch (Exception ex)
        {
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DV1_ItemDeleting", ex.Message, "", "c#", "0", ex.StackTrace);
        }
    }
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        var controlItem = new List<ControlItem>() 
        {
          new ControlItem("txtDEPT_ID", txtDEPT_ID.Text, txtDEPT_ID.GetType()),
          new ControlItem("txtCONTROL_NAME", txtDEPT_NAME.Text, txtDEPT_NAME.GetType())      
        };
        ConditionRecordUtil.RecordSearchConditionData(controlItem);

        DBINIT();
        lbl_Message.Text = string.Empty;
        if ((DV1.FindControl("DataPager1")) != null)
        {
            int PageSize = ((DataPager)DV1.FindControl("DataPager1")).PageSize;
            ((DataPager)DV1.FindControl("DataPager1")).SetPageProperties(0, PageSize, true);

            //Adams:設定頁數相關功能
            SetPagerInfo(PageSize);
        }
    }



    protected void DV1_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        string v_DEPT_ID, v_DEPT_NAME, v_PARENT_DEPT_ID, v_E_MAIL, v_USER_ID, v_COLUMN = "";
        string p_return_string;
        TextBox TB = new TextBox();
        try
        {
            v_DEPT_ID = ((TextBox)DV1.InsertItem.FindControl("txtDEPT_ID_G")).Text.Trim();
            // EmptyDataTemplate
            v_DEPT_NAME = ((TextBox)DV1.InsertItem.FindControl("txtDEPT_NAME_G")).Text.Trim();
            v_PARENT_DEPT_ID = ((TextBox)DV1.InsertItem.FindControl("txtPARENT_DEPT_ID")).Text.Trim();
            v_E_MAIL = ((TextBox)DV1.InsertItem.FindControl("txtE_MAIL")).Text.Trim();
            v_USER_ID = ((TextBox)DV1.InsertItem.FindControl("txtUSER_ID")).Text.Trim();

            TB = ((TextBox)DV1.InsertItem.FindControl("txtPARENT_DEPT_ID"));
            lbl_Message.Text = string.Empty;
            p_return_string = check(v_PARENT_DEPT_ID, v_E_MAIL, v_USER_ID, v_DEPT_ID);
            if (p_return_string != string.Empty)
            {
                switch (p_return_string)
                {
                    case "1":
                        lbl_Message.Text = "上層部門代號必需存在於部門代號檔中!";
                        v_COLUMN = "txtPARENT_DEPT_ID";
                        break;
                    case "2":
                        lbl_Message.Text = "部門主管或站所特定E_MAIL必需擇一輸入!";
                        v_COLUMN = "txtE_MAIL";
                        break;
                    case "3":
                        lbl_Message.Text = "使用者代號必需存在於使用者檔中!";
                        v_COLUMN = "txtUSER_ID";
                        break;
                    case "4":
                        lbl_Message.Text = v_PARENT_DEPT_ID + "-與部門代號(" + v_DEPT_ID + ")產生循環參考！";
                        v_COLUMN = "txtPARENT_DEPT_ID";
                        break;
                    case "5":
                        lbl_Message.Text = "E-Mail格式錯誤！";
                        v_COLUMN = "txtE_MAIL";
                        break;
                    default:
                        break;
                }


                TB = ((TextBox)DV1.InsertItem.FindControl(v_COLUMN));
                TB.Focus();
                e.Cancel = true;
            }
            else
            {

                //'==下面的程式，只是作SQL指令的更新動作而已
                //'== 設定SQL指令將會用到的參數 ==
                SDS_dept.InsertParameters.Clear();

                SDS_dept.InsertParameters.Add("DEPT_ID", v_DEPT_ID);
                SDS_dept.InsertParameters.Add("DEPT_NAME", v_DEPT_NAME);
                SDS_dept.InsertParameters.Add("PARENT_DEPT_ID", v_PARENT_DEPT_ID);
                SDS_dept.InsertParameters.Add("E_MAIL", v_E_MAIL);
                SDS_dept.InsertParameters.Add("USER_ID", v_USER_ID);
                SDS_dept.InsertParameters.Add("CRT_ID", User.Identity.Name);
                SDS_dept.InsertParameters.Add("CRT_DATE", System.DateTime.Now.ToString("yyyyMMdd"));
                SDS_dept.InsertParameters.Add("CRT_TIME", System.DateTime.Now.ToString("HHmmss"));
                SDS_dept.InsertParameters.Add("UPD_ID", User.Identity.Name);
                SDS_dept.InsertParameters.Add("UPD_DATE", System.DateTime.Now.ToString("yyyyMMdd"));
                SDS_dept.InsertParameters.Add("UPD_TIME", System.DateTime.Now.ToString("HHmmss"));


                SDS_dept.InsertCommand = "insert into MIS_DEPT_AP (DEPT_ID, DEPT_NAME, parent_DEPT_ID, E_MAIL,USER_ID, crt_id, crt_date, crt_time, upd_id, upd_date, upd_time) values(:DEPT_ID, :DEPT_NAME, :parent_DEPT_ID, :E_MAIL, :UESR_ID, :crt_id, :crt_date, :crt_time, :upd_id, :upd_date, :upd_time)";
                SDS_dept.Insert();
                //'==========================================
                DBINIT();
            }

        }

        catch (Exception ex)
        {
            //Response.Write(ex.Message);
            //PK重覆
            if (ex.Message.IndexOf("ORA-00001") >= 0)
            {
                lbl_Message.Text = "輸入的部門代號已存在部門檔中！";
            }
            else
            {
                lbl_Message.Text = ex.Message;
            }
            ERROR_DBSAVE("bas_dept.aspx.cs", "DV1_ItemInserting", ex.Message, "", "c#", "0", ex.StackTrace);

        }
    }

    protected void DV1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {

        if (hidSAVE.Value == "Y")
        {
            SAVE();
        }

        DV1.SelectedIndex = -1;
        //Adams:設定挑選的頁數變化
        DataPager dp = ((DataPager)DV1.FindControl("DataPager1")) as DataPager;
        SetGoToPageDropDownList(e.StartRowIndex, e.MaximumRows, dp.TotalRowCount);

    }
    protected void DV1_PagePropertiesChanged(object sender, EventArgs e)
    {
        int PageSize = ((DataPager)DV1.FindControl("DataPager1")).PageSize;
        int StartRowIndex = ((DataPager)DV1.FindControl("DataPager1")).StartRowIndex;
        int TotalRowCount = ((DataPager)DV1.FindControl("DataPager1")).TotalRowCount;
        ((DataPager)DV1.FindControl("DataPager1")).SetPageProperties(StartRowIndex, PageSize, true);

        DBINIT();
    }

    protected string check(string p_PARENT_DEPT_ID, string p_E_MAIL, string p_USER_ID, string p_DEPT_ID)
    {
        //判斷USER_ID、PARENT_DEPT_ID必需存在DEPT_ID
        lbl_Message.Text = string.Empty;
        if (p_USER_ID != string.Empty)
        {
            if (check_USER_ID(p_USER_ID) == string.Empty)
            {
                return "3";
            }
        }

        if (p_PARENT_DEPT_ID != string.Empty)
        {
            DataSourceSelectArguments args = new DataSourceSelectArguments();
            DataView DV = new DataView();

            SDS_dept.SelectCommand = "SELECT DEPT_ID FROM MIS_DEPT_AP Where DEPT_ID = :DEPT_ID ";
            SDS_dept.SelectParameters.Clear();
            SDS_dept.SelectParameters.Add("DEPT_ID", TypeCode.String, p_PARENT_DEPT_ID);

            //== 3.執行SQL指令 .select() ==
            SDS_dept.DataSourceMode = SqlDataSourceMode.DataSet;
            DV = (DataView)SDS_dept.Select(args);
            if (DV.Table.Rows.Count == 0)
            {
                return "1";
            }
            if (check_PARENT_DEPT_ID(p_DEPT_ID, p_PARENT_DEPT_ID) != string.Empty)
            {
                return "4";
            }

        }
        //判斷站所是否有輸入E_MAIL
        if (p_E_MAIL == string.Empty && p_USER_ID == string.Empty)
        {
            return "2";

        }

        if (p_E_MAIL != string.Empty)
        {
            if (IsValidEmail(p_E_MAIL) == false)
            {
                return "5";
            }


        }


        return string.Empty;
    }
    protected void txtUSER_ID_TextChanged(object sender, EventArgs e)
    {
        //帶出使用者姓名
        try
        {
            string v_USER_ID, v_USER_NAME;

            TextBox txtUSER_ID = sender as TextBox;

            if (txtUSER_ID != null)
            {
                v_USER_ID = txtUSER_ID.Text.Trim();
                v_USER_NAME = check_USER_ID(v_USER_ID);
                Label lit = txtUSER_ID.Parent.FindControl("lblUSER_NAME") as Label;
                if (v_USER_NAME != string.Empty)
                {
                    lit.Text = v_USER_NAME;
                }
                else
                {
                    //使用者代號不存在
                    lit.Text = "";
                    lbl_Message.Text = v_USER_ID + " -使用者代號不存在使用者檔中！";
                    txtUSER_ID.Focus();
                }
            }

        }
        catch (Exception ex)
        {
            //Response.Write(e.Message);
            lbl_Message.Text = ex.Message;

        }
    }
    protected string check_USER_ID(string p_USER_ID)
    {
        //判斷PARENT_DEPT_ID必需存在DEPT_ID
        string v_SQL;
        DataSourceSelectArguments args = new DataSourceSelectArguments();
        lbl_Message.Text = string.Empty;
        if (p_USER_ID != string.Empty)
        {
            //== 2.撰寫SQL指令 ==
            v_SQL = "SELECT  A.USER_ID,A.USER_NAME ";
            v_SQL = v_SQL + " FROM MIS_USER_AP A";
            v_SQL = v_SQL + " Where A.USER_ID = :USER_ID ";

            SDS_dept.SelectParameters.Clear();
            SDS_dept.SelectCommand = v_SQL;
            SDS_dept.SelectParameters.Add("USER_ID", TypeCode.String, p_USER_ID);

            //== 3.執行SQL指令 .select() ==
            SDS_dept.DataSourceMode = SqlDataSourceMode.DataSet;
            dv = (DataView)SDS_dept.Select(args);
            if (dv.Table.Rows.Count != 0)
            {
                return dv.Table.Rows[0]["USER_NAME"].ToString();
            }
            else
            {
                //使用者代號不存在
                return string.Empty;

            }

        }

        return string.Empty;
    }
    protected string check_PARENT_DEPT_ID(string p_DEPT_ID, string p_PARENT_DEPT_ID)
    {
        //判斷PARENT_DEPT_ID必需存在DEPT_ID
        string v_SQL;
        DataSourceSelectArguments args = new DataSourceSelectArguments();
        if (p_PARENT_DEPT_ID != string.Empty)
        {
            //== 2.撰寫SQL指令 ==
            v_SQL = "select * from mis_dept_ap A ";
            v_SQL = v_SQL + " where A.DEPT_ID = :PARENT_DEPT_ID ";
            v_SQL = v_SQL + " and exists ( select * ";
            v_SQL = v_SQL + " from( ";
            v_SQL = v_SQL + " Select DEPT_ID,DEPT_NAME from MIS_DEPT_AP ";
            v_SQL = v_SQL + " Start with DEPT_ID=:DEPT_ID ";
            v_SQL = v_SQL + " Connect by PARENT_DEPT_ID=prior DEPT_ID ";
            v_SQL = v_SQL + " ) Z ";
            v_SQL = v_SQL + " where A.DEPT_ID = Z.DEPT_ID ";
            v_SQL = v_SQL + " ) ";

            SDS_dept.SelectParameters.Clear();
            SDS_dept.SelectCommand = v_SQL;
            SDS_dept.SelectParameters.Add("PARENT_DEPT_ID", TypeCode.String, p_PARENT_DEPT_ID);
            SDS_dept.SelectParameters.Add("DEPT_ID", TypeCode.String, p_DEPT_ID);

            //== 3.執行SQL指令 .select() ==
            SDS_dept.DataSourceMode = SqlDataSourceMode.DataSet;
            dv = (DataView)SDS_dept.Select(args);
            if (dv.Table.Rows.Count == 0)
            {
                return string.Empty;
            }
            else
            {
                //表該傳入的PARENT_DEPT_ID 與DEPT_ID 循環參考
                return "1";

            }

        }

        return string.Empty;
    }
    protected void txtPARENT_DEPT_ID_TextChanged(object sender, EventArgs e)
    {
        try
        {
            string v_DEPT_ID, v_PARENT_DEPT_ID;

            TextBox txtPARENT_DEPT_ID = sender as TextBox;
            TextBox txtDEPT_ID = sender as TextBox;

            if (txtDEPT_ID != null)
            {
                v_PARENT_DEPT_ID = txtPARENT_DEPT_ID.Text.Trim();
                txtDEPT_ID = txtDEPT_ID.Parent.FindControl("txtDEPT_ID_G") as TextBox;
                v_DEPT_ID = txtDEPT_ID.Text;
                if (check_PARENT_DEPT_ID(v_DEPT_ID, v_PARENT_DEPT_ID) != string.Empty)
                {
                    //使用者代號不存在
                    lbl_Message.Text = v_PARENT_DEPT_ID + " -與部門代號(" + v_DEPT_ID + ")產生循環參考！";
                    txtPARENT_DEPT_ID.Focus();
                }
                else
                {
                    lbl_Message.Text = "";
                }
            }

        }
        catch (Exception ex)
        {
            //Response.Write(e.Message);
            lbl_Message.Text = ex.Message;
            ERROR_DBSAVE("bas_dept.aspx.cs", "txtPARENT_DEPT_ID_TextChanged", ex.Message, "", "c#", "0", ex.StackTrace);
        }
    }
    protected void btn_save_Click(object sender, EventArgs e)
    {
        if (SAVE() == "Y")
        {
            DBINIT();
        };


    }

    protected string SAVE()
    {
        string v_DEPT_ID, v_DEPT_NAME, v_PARENT_DEPT_ID, v_E_MAIL, v_USER_ID;
        string p_return_string, v_COLUMN = "";
        string v_flag = "";

        // OracleConnection conn = new OracleConnection("DataSource=xxxxxxx;UserId=xxxxxx;Password=xxxxxxxx;");
        try
        {
            foreach (ListViewDataItem item in DV1.Items)
            {
                if (item.ItemType == ListViewItemType.DataItem)//是資料列才往下處理
                {
                    //抓出各欄位的控制項
                    HiddenField hidCHANGED = (HiddenField)item.FindControl("hidCHANGED");
                    if (hidCHANGED.Value == "Y")
                    {

                        v_DEPT_ID = (string)DV1.DataKeys[item.DisplayIndex].Value;
                        // EmptyDataTemplate
                        v_DEPT_NAME = ((TextBox)item.FindControl("txtDEPT_NAME_G")).Text.Trim();
                        v_PARENT_DEPT_ID = ((TextBox)item.FindControl("txtPARENT_DEPT_ID")).Text.Trim();
                        v_E_MAIL = ((TextBox)item.FindControl("txtE_MAIL")).Text.Trim();
                        v_USER_ID = ((TextBox)item.FindControl("txtUSER_ID")).Text.Trim();

                        lbl_Message.Text = string.Empty;
                        p_return_string = check(v_PARENT_DEPT_ID, v_E_MAIL, v_USER_ID, v_DEPT_ID);
                        if (p_return_string != string.Empty)
                        {
                            v_flag = "N";
                            switch (p_return_string)
                            {
                                case "1":
                                    lbl_Message.Text = "上層部門代號必需存在於部門代號檔中!";
                                    v_COLUMN = "txtPARENT_DEPT_ID";
                                    break;
                                case "2":
                                    lbl_Message.Text = "部門主管或站所特定E-Mail必需擇一輸入！";
                                    v_COLUMN = "txtPARENT_DEPT_ID";
                                    break;
                                case "3":
                                    lbl_Message.Text = "使用者代號必需存在於使用者檔中!";
                                    v_COLUMN = "txtUSER_ID";
                                    break;
                                case "4":
                                    lbl_Message.Text = v_PARENT_DEPT_ID + "-與部門代號(" + v_DEPT_ID + ")產生循環參考！";
                                    v_COLUMN = "txtPARENT_DEPT_ID";
                                    break;
                                case "5":
                                    lbl_Message.Text = "E-Mail格式錯誤！";
                                    v_COLUMN = "txtE_MAIL";
                                    break;
                                default:
                                    break;
                            }

                            TextBox TB = new TextBox();
                            TB = ((TextBox)item.FindControl(v_COLUMN));
                            TB.Focus();

                            break;//離開foreach
                        }
                        else
                        {

                            //'==下面的程式，只是作SQL指令的更新動作而已
                            //'== 設定SQL指令將會用到的參數 ==
                            SDS_dept.UpdateParameters.Clear();
                            SDS_dept.UpdateParameters.Add("DEPT_NAME", v_DEPT_NAME);
                            SDS_dept.UpdateParameters.Add("PARENT_DEPT_ID", v_PARENT_DEPT_ID);
                            SDS_dept.UpdateParameters.Add("E_MAIL", v_E_MAIL);
                            SDS_dept.UpdateParameters.Add("USER_ID", v_USER_ID);
                            SDS_dept.UpdateParameters.Add("UPD_ID", User.Identity.Name);
                            SDS_dept.UpdateParameters.Add("UPD_DATE", System.DateTime.Now.ToString("yyyyMMdd"));
                            SDS_dept.UpdateParameters.Add("UPD_TIME", System.DateTime.Now.ToString("HHmmss"));
                            SDS_dept.UpdateParameters.Add("DEPT_ID", v_DEPT_ID);

                            SDS_dept.UpdateCommand = "UPDATE MIS_DEPT_AP SET DEPT_NAME = :DEPT_NAME, PARENT_DEPT_ID = :PARENT_DEPT_ID, E_MAIL = :E_MAIL, USER_ID = :UESR_ID, UPD_ID = :UPD_ID, UPD_DATE = :UPD_DATE, UPD_TIME = :UPD_TIME WHERE DEPT_ID = :DEPT_ID";
                            SDS_dept.Update();
                            v_flag = "Y";
                            //'==========================================

                        }
                    }

                }
                if (v_flag == "Y")
                {
                    //存檔成功
                }

            }
            return v_flag;
        }
        catch (Exception ex)
        {
            //Response.Write(e.Message);
            lbl_Message.Text = ex.Message;
            
            ERROR_DBSAVE("bas_dept.aspx.cs", "SAVE", ex.Message, "", "c#", "0", ex.StackTrace);
            return "N";
        }
    }
    private string DomainMapper(Match match)
    {
        // IdnMapping class with default property values.
        IdnMapping idn = new IdnMapping();

        string domainName = match.Groups[2].Value;
        try
        {
            domainName = idn.GetAscii(domainName);
        }
        catch (Exception ex)
        {
            //invalid = true;
            ERROR_DBSAVE("bas_dept.aspx.cs", "DomainMapper", ex.Message, "", "c#", "0", ex.StackTrace);
        }
        return match.Groups[1].Value + domainName;
    }
    public bool IsValidEmail(string strIn)
    {
        bool invalid = false;
        if (String.IsNullOrEmpty(strIn))
            return false;

        // Use IdnMapping class to convert Unicode domain names. 
        try
        {
            strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper,
                                  RegexOptions.None, TimeSpan.FromMilliseconds(200));
        }
        catch (Exception ex)
        {
            ERROR_DBSAVE("bas_dept.aspx.cs", "IsValidEmail", ex.Message, "", "c#", "0", ex.StackTrace);
            return false;
        }

        if (invalid)
            return false;

        // Return true if strIn is in valid e-mail format. 
        try
        {
            return Regex.IsMatch(strIn,
                  @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                  @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                  RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
        }
        catch (RegexMatchTimeoutException ex)
        {
            ERROR_DBSAVE("bas_dept.aspx.cs", "IsValidEmail1", ex.Message, "", "c#", "0", ex.StackTrace);
            return false;
        }
    }

    //protected void SDS_dept_Updated(object sender, SqlDataSourceStatusEventArgs e)
    //{
    //    if (e.Exception == null)
    //    {
    //        e.Command.Transaction.Commit();               
    //    } // if
    //    else
    //    {
    //        e.Command.Transaction.Rollback();   // commit()失敗--> rollback() 確保資料結構完整
    //        Response.Write( "資料更新失敗: " + e.Exception.Message );
    //    } // else
    //}
    //protected void SDS_dept_Updating(object sender, SqlDataSourceCommandEventArgs e)
    //{
    //    e.Command.Connection.Open();
    //    e.Command.Transaction = e.Command.Connection.BeginTransaction();
    //}

    //Adams:設定頁數相關功能
    protected void uxOnePageCountDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetPagerInfo(int.Parse(((DropDownList)sender).SelectedValue));
    }
    //Adams:設定頁數相關功能
    protected void uxGoToPageDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = sender as DropDownList;
        DataPager dp = (DataPager)DV1.FindControl("DataPager1") as DataPager;
        int StartRowIndex = int.Parse(((DropDownList)sender).SelectedValue) * dp.PageSize;
        dp.SetPageProperties(StartRowIndex, dp.PageSize, true);
    }

    protected void SetPagerInfo(int PageSize)
    {
        //Adams:顯示分頁處的總頁數
        DataPager dp = (DataPager)DV1.FindControl("DataPager1") as DataPager;
        dp.PageSize = PageSize;
        int PageCount = (dp.TotalRowCount / dp.PageSize) + 1;
        Label lbl_total_page_count = (Label)DV1.FindControl("lbl_total_page_count") as Label;
        lbl_total_page_count.Text = PageCount.ToString();
        Label lbl_total_counter = (Label)DV1.FindControl("lbl_total_counter") as Label;
        lbl_total_counter.Text = dp.TotalRowCount.ToString();
        //跳到指定頁數   
        SetGoToPageDropDownList(dp.StartRowIndex, dp.PageSize, dp.TotalRowCount);
    }

    //Adams:設定頁數相關功能
    protected void SetGoToPageDropDownList(int StartRowIndex, int PageSize, int TotalRowCount)
    {
        int PageIndex = StartRowIndex / PageSize;
        int PageCount = TotalRowCount / PageSize;
        DropDownList GoToPageDropDownList = DV1.FindControl("uxGoToPageDropDownList") as DropDownList;
        GoToPageDropDownList.Items.Clear();
        for (int i = 0; i <= PageCount; i++)
        {
            GoToPageDropDownList.Items.Add(new ListItem((i + 1).ToString(), i.ToString()));
        }
        GoToPageDropDownList.SelectedValue = (PageIndex).ToString();
    }

    protected void btn_exist_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }

}